package com.longrise.android.byjk.utils;

import android.content.Context;
import android.util.Base64;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * Created by callxkj on 2016/12/10.
 * 同步学习记录接口加密
 */

public class CourseEncryptionUtil {

    public static final String RSA = "RSA";// 非对称加密密钥算法
    public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式

    public static String courseEncrypty(Context context, String content) {
        String result = null;
        String pukey = CourseRKeyUtil.getbbCourseRKeyFromC(context);
        byte[] publickey = Base64.decode(pukey, Base64.DEFAULT);
        try {
            byte[] bytes = encryptByPublicKey(content.getBytes(), publickey);
            result = Base64.encodeToString(bytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 用公钥对字符串进行加密
     *
     * @param data 原文
     */
    private static byte[] encryptByPublicKey(byte[] data, byte[] publicKey)
            throws Exception {
        // 得到公钥
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PublicKey keyPublic = kf.generatePublic(keySpec);
        // 加密数据
        Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
        cp.init(Cipher.ENCRYPT_MODE, keyPublic);
        return cp.doFinal(data);
    }
}
